#!/bin/bash
# USAGE:
#	saveas exportFormat [optionalParameters] processName
#
# DESCRIPTION:
#  SAVEAS is an internal ADORE command. 
#  It prepares DORIS results so that they can be opened by other programs. 
#  Currently ENVI and ArcGIS are supported. 
#
# INPUT:
#  exportFormat: envi, arcgis, gdal, grd. 
#  processName: Doris step to be exported.
#  
#  Optional:
#    saveas arcgis [a|p|m] processName
#	arcgis export files (HFA, img files) can only have single channel (amplitude, phase or mixed).
#       If not specified p(phase) is assumed. This can be used to export amplitude data as well if 
#	you do not want to rescale the amplitude values. 
#    
#    saveas envi processName
#       Generates an ENVI header (*.hdr) file for the given input file. 
#       If file is complex, both real and imaginary channels can be opened
#       in ENVI. Only corner coordinates are used for geocoding. ArcGIS (*.img)
#       files can also be opened in ENVI if, geocoding of full image is required.
#
#    saveas gdal a|p|m processName [options for gdal] outputFileName
#       Generates a interim file and passes it to gdal_translate. The output
#       filename and all other parameters has to be input by the user. 
#
# OUTPUT:
#  ENVI:Generates an HDR file with the same name as the output file of the requested doris step (processName).
#  ArcGIS: Generates an IMG file.
#
# EXAMPLES:
#  saveas grd p unwrap
#  saveas arcgis p unwrap
#  saveas envi unwrap 
#  saveas gdal p unwrap -of GTiff 200405_200703_uw.tiff
#
 
# $0 dorisStep  
function saveas_envi(){
  local dorisStep=${1}
  local geocodeStatus phi_filename lam_filename phi_l0p0 lam_l0p0 phi_lNpN lam_lNpN phi_step lam_step
  local filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local bands rotation phi_lNp0 
  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    [ ! -f "${filename}" ] && error "File not found: ${filename}" && return
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`
    #get the coordinates for 1st px
    phi_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`
    #get the coordinates for last px on 1st line
    # lam = longitude so divide by numpix
    lam_l0pN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p${hei_numpixels} -P${hei_numpixels} ${lam_filename} 2>/dev/null | tr -d "\n"`
    lam_step=`echo "${lam_l0pN} ${lam_l0p0} ${numpixels}" | awk '{printf "%e", ($1-$2)/$3};'`
    #get the coordinates for last line on 1st col.(pixel)
    # phi is latitude so divide by numlines
    phi_lNp0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p1 -P1 ${phi_filename} 2>/dev/null | tr -d "\n"`        
	# Below line has a problem without -1 multiplier in Envi. 
    phi_step=`echo "${phi_lNp0} ${phi_l0p0} ${numlines}"  | awk '{printf "%e", -1*($1-$2)/$3};'` 
    #calculate rotation
    lam_lNp0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`
    rotation=`echo "${phi_lNp0} ${phi_l0p0} ${lam_lNp0} ${lam_l0p0}" | awk '{PI=3.1415;printf "%.8f", 90+(atan2($1-$2, $3-$4)*180/PI)};'`
    #change format to envi 
    [ "${format}" == "cr4" ] && format="4" && bands="2"
    [ "${format}" == "ci2" ] && format="2" && bands="2"
    [ "${format}" == "r4" ] && format="4"  && bands="1"
    [ "${format}" == "i2" ] && format="2"  && bands="1"
cat > ${filename}.hdr <<_EndHere
ENVI
description = {DORIS ${dorisStep} output: ${filename}}
samples = ${numpixels}
lines   = ${numlines}
bands   = ${bands}
header offset = 0
file type = ENVI Standard
data type = ${format}
interleave = bip
sensor type = Unknown
byte order = 0
map info = {Geographic Lat/Lon, 1.5000, 1.5000, ${lam_l0p0}, ${phi_l0p0}, ${lam_step}, ${phi_step}, WGS-84, units=Degrees, rotation=${rotation}}
default bands = {1}
wavelength units = Unknown

_EndHere
#    band names = {}
    echo "ENVI header file: ${filename}.hdr"
    echo "SUCCESS: saveas_envi"
  else
    echo "Please first do the geocoding step to export to ENVI."
  fi
}

function saveas_arcgis(){
  dorisStep=${1}
  local geocodeStatus phi_filename lam_filename phi_l0p0 lam_l0p0 phi_lNpN lam_lNpN phi_step lam_step
  local filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local bands endian

  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`
    #get the coordinates for 1st px
    phi_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`
    #get the coordinates for last px on 1st line
    phi_l0pN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p${hei_numpixels} -P${hei_numpixels} ${phi_filename} 2>/dev/null | tr -d "\n"`
    phi_step=`echo "${phi_l0pN} ${phi_l0p0} ${numpixels}" | awk '{printf "%.8f", ($1-$2)/$3};'`
    #get the coordinates for last line on 1st col.(pixel)
    lam_lNp0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`        
    lam_step=`echo "${lam_lNp0} ${lam_l0p0} ${numlines}"  | awk '{printf "%.8f", ($1-$2)/$3};'`
    #change format to arcgis
    [ ${format} == "cr4" ] && format="32" && bands="2"
    [ ${format} == "ci2" ] && format="16" && bands="2"
    [ ${format} == "r4" ] && format="32"  && bands="1"
    [ ${format} == "i2" ] && format="16"  && bands="1"
    endian=`getSystemEndianness`
    [ ${endian} == "little" ] && endian="I"
    [ ${endian} == "big"    ] && endian="M"
cat > ${filename}.hdr <<_EndHere
BYTEORDER	${endian}
LAYOUT		BIP
NROWS		${numlines}
NCOLS		${numpixels}
NBANDS		${bands}
NBITS		${format}
NODATA		-9999
ULXMAP		${phi_l0p0}
ULYMAP		${lam_l0p0}
XDIM		${phi_step}
YDIM		%{lam_step}
_EndHere
    #xllcorner     0
    #yllcorner     0
    echo "ArcGIS header file: ${filename}.hdr"
    echo "SUCCESS: saveas_arcgis"
  else
    echo "Please first do the geocoding step to export to ArcGIS."
  fi
}


function saveas_arcgis_gdal(){
  local generate dorisStep geocodeStatus filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local generateCheck phi_filename lam_filename slc_rg_res_km slc_az_res_km center_lat center_lon slc_res_deg region 
  local inc_angle radar_band_width
 
  if [ ${2:-undefined} == "undefined" ]; then
    generate="p"; echo "You only specified one parameter. I'm assuming you wanted (p)phase output."
    dorisStep=${1}
  else
    generate=${1}
    dorisStep=${2}
  fi

  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    echo "..width..${numpixels}.."
    echo "..format..${format}.."
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`

    #generate file (amplitude, phase) to export
    generate=`echo ${generate} | tr [:upper:] [:lower:]`
    if [ "${#generate}" -gt "1" ]; then
      echo "I can only convert one product (a-amplitude, p-phase or m-mixed) at a time."
      return;
    fi
    generateCheck=`echo ${generate} | tr -d [a,p,m]`
    if [ -z ${generateCheck} ]; then
      echo -n "You requested me to generate: "
      [ ${generate} == 'a' ] && echo "amplitude"
      [ ${generate} == 'p' ] && echo "phase"
      [ ${generate} == 'm' ] && echo "mixed"
    else
      echo "I can only create phase(p), amplitude(a) or mixed(m) images."
      echo "You provided some extra options: ${generateCheck}"
      return -1;
    fi
    if [ -z ${filename} ]; then
      echo "No data file for the step ${dorisStep} in ${resfile}"
      return;
    fi
    outName=`basename ${filename}| tr '.' '_'`
    if [[ "${generate}" == *a* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q mag  -o float   ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *p* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else 
        cpxfiddle -w ${numpixels} -f ${format} -q phase  -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *m* ]]; then
      if [[ ${#format} -eq 2 ]];then
        echo "Mixed (Amp/Phase) output can not be generated using a real file. Image format: ${format}"
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -s 1.2 -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    fi

    #generate a 3 column data file combining phi lam hei
    gmtconvert ${lam_filename} ${phi_filename} ${outName}.temporary -bis1 -A -bos3 > ${outName}.dat
    #get pixel size in degrees
	#################DUPLICATED CODE FROM scr/fun/dem. Make lines below a function
        radar_band_width=`readRes.sh ${m_resfile} readfiles Total_range_band_width | tr -d '\n'`
        echo "Radar Band Width=${radar_band_width}"
        if [ -e ${i_resfile} ]; then
          inc_angle=`readRes.sh ${i_resfile} coarse_orbits inc_angle | tr -d '\n'`
        fi
        [ -z "${inc_angle}" ] && echo -e "Can not read incidence angle from ${i_resfile}. \n Using default:23.2" && inc_angle=23.2
        # get range resolution
        [ -z "${slc_rg_res}" ] && slc_rg_res=`echo "2.99e8 ${radar_band_width} ${inc_angle}" | awk '{PI=3.14159;printf "%d", $1/($2*1e6*cos($3/180*PI))};'`
        [ -z "${slc_az_res}" ] && slc_az_res=`echo "${slc_rg_res}" | awk '{printf "%d", $1/5};'`
        echo "SLC resolution [Azimuth x Range]: ${slc_az_res} x ${slc_rg_res}"
	#################END DUPLICATE
    dorisStep=`pn2rs ${2}`  #readRes.sh does not call pn2rs automatically...
    rg_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_range_direction"`    
    az_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_azimuth_direction"`    
    slc_rg_res_km=`echo "${slc_rg_res} ${rg_multilooking}" | awk '{printf "%f", $1*$2/1000};'`
    slc_az_res_km=`echo "${slc_az_res} ${az_multilooking}" | awk '{printf "%f", $1*$2/1000};'`	
    ## get center coordinates
    center_lat=`readRes.sh ${m_resfile} readfiles Scene_centre_latitude | tr -d '\n'`
    center_lon=`readRes.sh ${m_resfile} readfiles Scene_centre_longitude | tr -d '\n'`
    slc_res_deg=`${ADORESCR}/km2deg.sh ${center_lat} ${center_lon} ${slc_az_res_km} ${slc_rg_res_km}`
    [ $? -ne 0 ] && echo "Error running command: ${ADORESCR}/km2deg.sh ${center_lat} ${center_lon} ${slc_az_res_km} ${slc_rg_res_km}" && return 1
    slc_res_deg=${slc_res_deg/ /\/}
    #need to get the region for gmt 
    region=`minmax -I${slc_res_deg} -bis3 ${outName}.dat` 
    search_area=`echo "${slc_res_deg}" | awk '{printf "%f", $1*2};'`
    [ $? -ne 0 ] && echo "Error running command: minmax -I${slc_res_deg} -bis3 ${outName}.dat" && return 1
    #generate grd file
    xyz2grd ${outName}.dat -bis3 -G${outName}.grd ${region} -I${slc_res_deg} -N32767 -V || { echo "Error running command: $_"; return 1; }
    #nearneighbor ${outName}.dat -bis3 -G${outName}.grd ${region} -I${slc_res_deg} -N2 -S${search_area} -E32767 -V || { echo "Error running command: $_"; return 1; }
    #change grid to the older format (gdal complienat)
    grdreformat ${outName}.grd ${outName}_grdreformat.grd=sf -V || { echo "Error running command: $_"; return 1; }
    #translate the grd to HFA(img) format using gdal
    gdal_translate -a_nodata 32767 -co "STATISTICS=YES" -of HFA ${outName}_grdreformat.grd ${outName}.img 
    if [ $? -ne 0 ]; then
      echo "gdal_translate failed. I was trying to run: gdal_translate -a_nodata 32767 -co "STATISTICS=YES" -of HFA ${outName}_grdreformat.grd ${outName}.img";
      echo "I might have left behind temporary files: ${outName}.temporary ${outName}_grdreformat.grd ${outName}.grd ${outName}.dat"
      return
    else
      #cleanup
      rm -rf ${outName}.temporary ${outName}_grdreformat.grd ${outName}.grd ${outName}.dat
      echo "ArcGIS filename: ${outName}.img"
      echo "SUCCESS: saveas_arcgis"
    fi
  else
    echo "Please first do the geocoding step to export to ArcGIS."
  fi
}

function saveas_grd(){
  local generate dorisStep geocodeStatus filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local generateCheck phi_filename lam_filename slc_rg_res_km slc_az_res_km center_lat center_lon slc_res_deg region 
  local inc_angle radar_band_width
 
  if [ ${2:-undefined} == "undefined" ]; then
    generate="p"; echo "You only specified one parameter. I'm assuming you wanted (p)phase output."
    dorisStep=${1}
  else
    generate=${1}
    dorisStep=${2}
  fi

  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    echo "..width..${numpixels}.."
    echo "..format..${format}.."
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`
    dorisStep=${dorisStep%:*}
    
    #generate file (amplitude, phase) to export
    generate=`echo ${generate} | tr [:upper:] [:lower:]`
    if [ "${#generate}" -gt "1" ]; then
      echo "I can only convert one product (a-amplitude, p-phase or m-mixed) at a time."
      return;
    fi
    generateCheck=`echo ${generate} | tr -d [a,p,m]`
    if [ -z ${generateCheck} ]; then
      echo -n "You requested me to generate: "
      [ ${generate} == 'a' ] && echo "amplitude"
      [ ${generate} == 'p' ] && echo "phase"
      [ ${generate} == 'm' ] && echo "mixed"
    else
      echo "I can only create phase(p), amplitude(a) or mixed(m) images."
      echo "You provided some extra options: ${generateCheck}"
      return -1;
    fi
    if [ -z ${filename} ]; then
      echo "No data file for the step ${dorisStep} in ${resfile}"
      return;
    fi
    outName=`basename ${filename}| tr '.' '_'`
    if [[ "${generate}" == *a* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q mag  -o float   ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *p* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else 
        cpxfiddle -w ${numpixels} -f ${format} -q phase  -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *m* ]]; then
      if [[ ${#format} -eq 2 ]];then
        echo "Mixed (Amp/Phase) output can not be generated using a real file. Image format: ${format}"
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -s 1.2 -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    fi

    #generate a 3 column data file combining phi lam hei
    gmtconvert ${lam_filename} ${phi_filename} ${outName}.temporary -bis1 -A -bos3 > ${outName}.dat
    #get pixel size in degrees
	#################DUPLICATED CODE FROM scr/fun/dem. Make lines below a function
        radar_band_width=`readRes.sh ${m_resfile} readfiles Total_range_band_width | tr -d '\n'`
        echo "Radar Band Width=${radar_band_width}"
        if [ -e ${i_resfile} ]; then
          inc_angle=`readRes.sh ${i_resfile} coarse_orbits inc_angle | tr -d '\n'`
        fi
        [ -z "${inc_angle}" ] && echo -e "Can not read incidence angle from ${i_resfile}. \n Using default:23.2" && inc_angle=23.2
        # get range resolution
        [ -z "${slc_rg_res}" ] && slc_rg_res=`echo "2.99e8 ${radar_band_width} ${inc_angle}" | awk '{PI=3.14159;printf "%d", $1/($2*1e6*cos($3/180*PI))};'`
        [ -z "${slc_az_res}" ] && slc_az_res=`echo "${slc_rg_res}" | awk '{printf "%d", $1/5};'`
        echo "SLC resolution [Azimuth x Range]: ${slc_az_res} x ${slc_rg_res}"
	#################END DUPLICATE
    dorisStep=`pn2rs ${dorisStep}`  #readRes.sh does not call pn2rs automatically...
    rg_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_range_direction"`    
    az_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_azimuth_direction"`    
    slc_rg_res_km=`echo "${slc_rg_res} ${rg_multilooking}" | awk '{printf "%f", $1*$2/1000};'`
    slc_az_res_km=`echo "${slc_az_res} ${az_multilooking}" | awk '{printf "%f", $1*$2/1000};'`	
    ## get center coordinates
    center_lat=`readRes.sh ${m_resfile} readfiles Scene_centre_latitude | tr -d '\n'`
    #center_lon=`readRes.sh ${m_resfile} readfiles Scene_centre_longitude | tr -d '\n'` 
    slc_az_res_deg=`${ADORESCR}/km2deg.sh ${center_lat} 0 ${slc_az_res_km}`
    slc_az_res_deg=${slc_az_res_deg/ */}
    slc_rg_res_deg=`${ADORESCR}/km2deg.sh ${center_lat} 0 ${slc_rg_res_km}`    
    slc_rg_res_deg=${slc_rg_res_deg/ */}        
    #[ $? -ne 0 ] && echo "Error running command: ${ADORESCR}/km2deg.sh ${center_lat} ${center_lon} ${slc_az_res_km} ${slc_rg_res_km}" && return 1
    #slc_res_deg=${slc_res_deg/ /\/}
    slc_res_deg="${slc_az_res_deg}\\${slc_rg_res_deg}"
    #need to get the region for gmt 
    region=`minmax -I${slc_res_deg} -bis3 ${outName}.dat` 
    [ $? -ne 0 ] && echo "Error running command: minmax -I${slc_res_deg} -bis3 ${outName}.dat" && return 1
    #generate grd file
    xyz2grd ${outName}.dat -bis3 -G${outName}_default.grd ${region} -I${slc_res_deg} -V || { echo "Error running command: $_"; return 1; } #-N32767 
    #change grid to the older format (gdal compliant)
    grdreformat ${outName}_default.grd ${outName}.grd=sf -V || { echo "Error running command: $_"; return 1; }
    if [ $? -ne 0 ]; then
      echo "saveas_grd failed."
      echo "I might have left behind temporary files: ${outName}.temporary ${outName}.dat ${outName}_default.grd"
      return
    else
      #cleanup
      rm -rf ${outName}.temporary ${outName}.dat ${outName}_default.grd
      echo "GRD filename: ${outName}.grd"
      echo "SUCCESS: saveas_grd"
    fi
  else
    echo "Please first do the geocoding step to export to GRD format."
  fi
}

function saveas_ascii(){
  local generate dorisStep geocodeStatus filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local generateCheck phi_filename lam_filename slc_rg_res_km slc_az_res_km center_lat center_lon slc_res_deg region 
  local inc_angle radar_band_width
 
  if [ ${2:-undefined} == "undefined" ]; then
    generate="p"; echo "You only specified one parameter. I'm assuming you wanted (p)phase output."
    dorisStep=${1}
  else
    generate=${1}
    dorisStep=${2}
  fi

  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    echo "..width..${numpixels}.."
    echo "..format..${format}.."
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`
    dorisStep=${dorisStep%:*}
    
    #generate file (amplitude, phase) to export
    generate=`echo ${generate} | tr [:upper:] [:lower:]`
    if [ "${#generate}" -gt "1" ]; then
      echo "I can only convert one product (a-amplitude, p-phase or m-mixed) at a time."
      return;
    fi
    generateCheck=`echo ${generate} | tr -d [a,p,m]`
    if [ -z ${generateCheck} ]; then
      echo -n "You requested me to generate: "
      [ ${generate} == 'a' ] && echo "amplitude"
      [ ${generate} == 'p' ] && echo "phase"
      [ ${generate} == 'm' ] && echo "mixed"
    else
      echo "I can only create phase(p), amplitude(a) or mixed(m) images."
      echo "You provided some extra options: ${generateCheck}"
      return -1;
    fi
    if [ -z ${filename} ]; then
      echo "No data file for the step ${dorisStep} in ${resfile}"
      return;
    fi
    outName=`basename ${filename}| tr '.' '_'`
    if [[ "${generate}" == *a* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q mag  -o float   ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *p* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else 
        cpxfiddle -w ${numpixels} -f ${format} -q phase  -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *m* ]]; then
      if [[ ${#format} -eq 2 ]];then
        echo "Mixed (Amp/Phase) output can not be generated using a real file. Image format: ${format}"
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -s 1.2 -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    fi

    #generate a 3 column data file combining phi lam hei
    gmtconvert ${lam_filename} ${phi_filename} ${outName}.temporary -bis1 -A > ${outName}.dat
    #cleanup
    rm -rf ${outName}.temporary
    echo "ASCII filename: ${outName}.dat"
    echo "SUCCESS: saveas_ascii"
  else
    echo "Please first do the geocoding step to export to ASCII format."
  fi
}

function saveas_gdal(){
  local generate dorisStep geocodeStatus filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local generateCheck phi_filename lam_filename slc_rg_res_km slc_az_res_km center_lat center_lon slc_res_deg region 
  local inc_angle radar_band_width
 
  if [ "${2:-undefined}" == "undefined" ]; then
    error "Please check usage. Missing parameters."
  else
    generate=${1}
    shift
    dorisStep=${1}
    shift
  fi

  #check if filename is specified with dorisStep
  if [[ "${dorisStep}" == *:* ]]; then
    local inputFileName=`eval echo ${dorisStep#*:}`
    dorisStep=${dorisStep%:*}
    [ ! -e "${inputFileName}" ] && { echo "Can not find specified file: ${inputFileName}"; return 1; }
  fi

  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
    echo "..width..${numpixels}.."
    echo "..format..${format}.."
    #if specified change fileName to inputFileName
    [ "${inputFileName:-undefined}" != "undefined" ] && filename=${inputFileName};
    
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`

    #generate file (amplitude, phase) to export
    generate=`echo ${generate} | tr [:upper:] [:lower:]`
    if [ "${#generate}" -gt "1" ]; then
      echo "I can only convert one product (a-amplitude, p-phase or m-mixed) at a time."
      return;
    fi
    generateCheck=`echo ${generate} | tr -d [a,p,m]`
    if [ -z ${generateCheck} ]; then
      echo -n "You requested me to generate: "
      [ ${generate} == 'a' ] && echo "amplitude"
      [ ${generate} == 'p' ] && echo "phase"
      [ ${generate} == 'm' ] && echo "mixed"
    else
      echo "I can only create phase(p), amplitude(a) or mixed(m) images."
      echo "You provided some extra options: ${generateCheck}"
      return -1;
    fi
    if [ -z ${filename} ]; then
      echo "No data file for the step ${dorisStep} in ${resfile}"
      return;
    fi
    outName=`basename ${filename}| tr '.' '_'`
    if [[ "${generate}" == *a* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -q mag  -o float   ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *p* ]]; then
      if [[ ${#format} -eq 2 ]];then
        cpxfiddle -w ${numpixels} -f ${format} -q normal -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      else 
        cpxfiddle -w ${numpixels} -f ${format} -q phase  -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    elif [[ "${generate}" == *m* ]]; then
      if [[ ${#format} -eq 2 ]];then
        echo "Mixed (Amp/Phase) output can not be generated using a real file. Image format: ${format}"
      else
        cpxfiddle -w ${numpixels} -f ${format} -e 0.5 -s 1.2 -o float ${filename} > ${outName}.temporary || { echo "Error running command: $_"; return 1; }
      fi
    fi

    #generate a 3 column data file combining phi lam hei
    gmtconvert ${lam_filename} ${phi_filename} ${outName}.temporary -bis1 -A -bos3 > ${outName}.dat
    #get pixel size in degrees
	#################DUPLICATED CODE FROM scr/fun/dem. Make lines below a function
        radar_band_width=`readRes.sh ${m_resfile} readfiles Total_range_band_width | tr -d '\n'`
        echo "Radar Band Width=${radar_band_width}"
        if [ -e ${i_resfile} ]; then
          inc_angle=`readRes.sh ${i_resfile} coarse_orbits inc_angle | tr -d '\n'`
        fi
        [ -z "${inc_angle}" ] && echo -e "Can not read incidence angle from ${i_resfile}. \n Using default:23.2" && inc_angle=23.2
        # get range resolution
        [ -z "${slc_rg_res}" ] && slc_rg_res=`echo "2.99e8 ${radar_band_width} ${inc_angle}" | awk '{PI=3.14159;printf "%d", $1/($2*1e6*cos($3/180*PI))};'`
        [ -z "${slc_az_res}" ] && slc_az_res=`echo "${slc_rg_res}" | awk '{printf "%d", $1/5};'`
        echo "SLC resolution [Azimuth x Range]: ${slc_az_res} x ${slc_rg_res}"
	#################END DUPLICATE
    dorisStep=`pn2rs ${dorisStep}`  #readRes.sh does not call pn2rs automatically...
    rg_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_range_direction"`    
    az_multilooking=`${ADORESCR}/readRes.sh ${i_resfile} ${dorisStep} "Multilookfactor_azimuth_direction"`    
    slc_rg_res_km=`echo "${slc_rg_res} ${rg_multilooking}" | awk '{printf "%f", $1*$2/1000};'`
    slc_az_res_km=`echo "${slc_az_res} ${az_multilooking}" | awk '{printf "%f", $1*$2/1000};'`	
    ## get center coordinates
    center_lat=`readRes.sh ${m_resfile} readfiles Scene_centre_latitude | tr -d '\n'`
    center_lon=`readRes.sh ${m_resfile} readfiles Scene_centre_longitude | tr -d '\n'`
    slc_res_deg=`${ADORESCR}/km2deg.sh ${center_lat} ${center_lon} ${slc_az_res_km} ${slc_rg_res_km}`
    [ $? -ne 0 ] && echo "Error running command: ${ADORESCR}/km2deg.sh ${center_lat} ${center_lon} ${slc_az_res_km} ${slc_rg_res_km}" && return 1
    slc_res_deg=${slc_res_deg/ /\/}
    #need to get the region for gmt 
    region=`minmax -I${slc_res_deg} -bis3 ${outName}.dat` 
    [ $? -ne 0 ] && echo "Error running command: minmax -I${slc_res_deg} -bis3 ${outName}.dat" && return 1
    #generate grd file
    xyz2grd ${outName}.dat -bis3 -G${outName}.grd ${region} -I${slc_res_deg} -N32767 -V || { echo "Error running command: $_"; return 1; }
    #change grid to the older format (gdal compliant)
    grdreformat ${outName}.grd ${outName}_grdreformat.grd=sf -V || { echo "Error running command: $_"; return 1; }
    #translate the grd to HFA(img) format using gdal
    gdal_translate -a_nodata 32767 ${outName}_grdreformat.grd ${@}
    if [ $? -ne 0 ]; then
      echo "gdal_translate failed. I was trying to run: gdal_translate ${outName}_grdreformat.grd ${@}";
      echo "I might have left behind temporary files: ${outName}.temporary ${outName}_grdreformat.grd ${outName}.grd ${outName}.dat"
      return
    else
      #cleanup
      rm -rf ${outName}.temporary ${outName}_grdreformat.grd ${outName}.grd ${outName}.dat
      echo "SUCCESS: saveas_gdal"
    fi
  else
    echo "Please first do the geocoding step to export in GDAL formats."
  fi
}

function saveas_giant(){
  dorisStep=${1}
  local geocodeStatus phi_filename lam_filename phi_l0p0 lam_l0p0 phi_lNpN lam_lNpN phi_step lam_step
  local filename resfile format numpixels numlines hei_filename hei_resfile hei_format hei_numpixels hei_numlines
  local bands endian
  local hdrname
  local kmlfile A north south east west x y 

  call "(filename resfile format numpixels numlines)=dorisProcess2OutputFile ${dorisStep}"
  hdrname="${filename}.rsc"  
  geocodeStatus=`check ${i_resfile} | grep -i -w "geocoding"| cut -f2 -d:`
  if [ ${geocodeStatus} -eq "1" ]; then
    call "(hei_filename hei_resfile hei_format hei_numpixels hei_numlines)=dorisProcess2OutputFile geocode Data_output_file_hei"
    # get the name of phi(lat) and lambda (lon) files
    phi_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_phi`
    lam_filename=`readRes.sh ${i_resfile} geocoding Data_output_file_lamda`
    #get the coordinates for 1st px
    phi_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_l0p0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`
    #get the coordinates for last px on 1st line
    phi_l0pN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p${hei_numpixels} -P${hei_numpixels} ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_l0pN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l1 -L1 -p${hei_numpixels} -P${hei_numpixels} ${lam_filename} 2>/dev/null | tr -d "\n"`
    phi_step=`echo "${phi_l0pN} ${phi_l0p0} ${numpixels}" | awk '{printf "%.8f", ($1-$2)/$3};'`
    #get the coordinates for last line on 1st col.(pixel)
    phi_lNp0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p1 -P1 ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_lNp0=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p1 -P1 ${lam_filename} 2>/dev/null | tr -d "\n"`        
    lam_step=`echo "${lam_lNp0} ${lam_l0p0} ${numlines}"  | awk '{printf "%.8f", ($1-$2)/$3};'`
    #get the coordinates for last line on last col.(pixel)
    phi_lNpN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p${hei_numpixels} -P${hei_numpixels} ${phi_filename} 2>/dev/null | tr -d "\n"`
    lam_lNpN=`cpxfiddle -w ${hei_numpixels} -f ${hei_format} -qnormal -l${hei_numlines} -L${hei_numlines} -p${hei_numpixels} -P${hei_numpixels} ${lam_filename} 2>/dev/null | tr -d "\n"`        
    # create the rsc file
    echo "WIDTH               ${numpixels}"> ${hdrname}
    echo "FILE_LENGTH         ${numlines}" >> ${hdrname}
    echo "LAT_REF1            ${lam_l0p0}" >> ${hdrname}
    echo "LON_REF1            ${phi_l0p0}" >> ${hdrname}
    echo "LAT_REF2            ${lam_l0pN}" >> ${hdrname}
    echo "LON_REF2            ${phi_l0pN}" >> ${hdrname}
    echo "LAT_REF3            ${lam_lNp0}" >> ${hdrname}
    echo "LON_REF3            ${phi_lNp0}" >> ${hdrname}
    echo "LAT_REF4            ${lam_lNpN}" >> ${hdrname}
    echo "LON_REF4            ${phi_lNpN}" >> ${hdrname}
    echo "AZIMUTH_PIXEL_SIZE  ${lam_step}" >> ${hdrname}
    echo "RANGE_PIXEL_SIZE    ${phi_step}" >> ${hdrname}
  else
    echo "Using approximate lat/lon coordinates from KML. Should be OK for Giant".
    # the coordinate calculations are based on an euclidian geometry and might not be very accurate
    # see http://stackoverflow.com/questions/1624574/calculate-lat-lng-of-corners-of-ground-overlay-from-kml-file
    if [ -f "${i12sFolder}/resample.kml" ]; then
      kmlfile="${i12sFolder}/resample.kml"
    elif [ -f ${resampleFolder}/*_${master}/resample.kml ]; then
      kmlfile="${resampleFolder}/*_${master}/resample.kml"
    else
      error "Can not find resample.kml file."
      return 
    fi
    A=`grep rotation ${kmlfile} |tr "<" ">"| cut -d">" -f3`
    north=`grep north ${kmlfile} |tr "<" ">"| cut -d">" -f3`
    south=`grep south ${kmlfile} |tr "<" ">"| cut -d">" -f3`
    east=`grep east ${kmlfile} |tr "<" ">"| cut -d">" -f3`
    west=`grep west ${kmlfile} |tr "<" ">"| cut -d">" -f3`
    cy=`echo ${north} ${south} | awk '{print ($1+$2)/2}'` # center lat
    cx=`echo ${east} ${west} | awk '{print ($1+$2)/2}'`   # center lon 
    x=`echo ${east} ${west} | awk '{print ($1-$2)/2}'`    # width lon
    y=`echo ${north} ${south} | awk '{print ($1-$2)/2}'`  # width lat
    A=`echo ${A} | awk '{print $1*3.14159265/180}'`
    nex=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 + $3*cos($5) - $4*sin($5)}'` # north east x lon
    ney=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 + $3*sin($5) + $4*cos($5)}'`
    nwx=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 - $3*cos($5) - $4*sin($5)}'`
    nwy=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 - $3*sin($5) + $4*cos($5)}'`
    sex=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 + $3*cos($5) + $4*sin($5)}'`
    sey=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 + $3*sin($5) - $4*cos($5)}'`
    swx=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $1 - $3*cos($5) + $4*sin($5)}'`
    swy=`echo ${cx} ${cy} ${x} ${y} ${A} | awk '{print $2 - $3*sin($5) - $4*cos($5)}'` # south west y lat
    # resolution
    phi_step=`echo "${nex} ${nwy} ${numpixels}"  | awk 'function abs(x){return ((x <0.0 )? -x : x)} {printf "%.8f", abs($1-$2)/$3};'`
    lam_step=`echo "${ney} ${sey} ${numlines}"   | awk 'function abs(x){return ((x <0.0 )? -x : x)} {printf "%.8f", abs($1-$2)/$3};'`
    # create the rsc file
    echo "WIDTH               ${numpixels}" > ${hdrname}
    echo "FILE_LENGTH         ${numlines}"  >> ${hdrname}
    echo "LAT_REF1            ${nwy}" >> ${hdrname}
    echo "LON_REF1            ${nwx}" >> ${hdrname}
    echo "LAT_REF2            ${swy}" >> ${hdrname}
    echo "LON_REF2            ${swx}" >> ${hdrname}
    echo "LAT_REF3            ${sey}" >> ${hdrname}
    echo "LON_REF3            ${sex}" >> ${hdrname}
    echo "LAT_REF4            ${ney}" >> ${hdrname}
    echo "LON_REF4            ${nex}" >> ${hdrname}
    echo "AZIMUTH_PIXEL_SIZE  ${lam_step}" >> ${hdrname}
    echo "RANGE_PIXEL_SIZE    ${phi_step}" >> ${hdrname}   
  fi
  echo "GIANT header file: ${hdrname}"
  echo "SUCCESS: saveas_giant"
}



case ${1} in 
  envi)
    [ $# -gt 2 ] && "Please check usage: ? saveas"      
    saveas_envi ${2}    
  ;;
  arcgis)
    saveas_arcgis_gdal ${2} ${3}
  ;;
  gdal*)
    shift
    saveas_gdal ${@}
  ;;
  grd)
    shift
    saveas_grd ${@}
  ;;
  ascii)
    shift
    saveas_ascii ${@}
  ;;
  giant)
    shift
    saveas_giant ${@}
  ;;
esac
